import XLSX from 'xlsx';
import { importCellularCompete } from './api';
import { Notification } from 'element-ui';

export default {
  name: 'import-competes-modal',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    topChannelList: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      formValue: {},
      formRules: {
        topChannelCode: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.topChannelCode) {
                callback('顶级渠道不能为空');
              } else {
                callback();
              }
            },
          },
        ],
        competes: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.competeStores) {
                callback('导入信息不能为空');
              } else {
                callback();
              }
            },
          },
        ],
      },
      formLabelWidth: '100px',
      resultVisible: false,
      tipData: [],
    };
  },
  watch: {},
  methods: {
    async onSubmit(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          try {
            this.tipData = await importCellularCompete(this.formValue);
            if (this.tipData.length > 0) {
              this.resultVisible = true;
            }
            this.onClose();
            this.resetTable();
            Notification({
              title: '提示',
              message: '导入成功',
              type: 'success',
            });
          } catch (e) {
            Notification({
              title: '错误',
              message: e.message,
              type: 'error',
            });
          }
        }
      });
    },
    resetTable() {
      this.$emit('resetTable');
    },
    onClose() {
      this.formValue = {};
      this.$refs.formRef.resetFields();
      this.$refs.upload.uploadFiles = [];
      this.$emit('close');
    },
    onChange(file) {
      const reader = new FileReader();
      reader.onload = e => {
        let data = e.target.result;
        const workbook = XLSX.read(data, { type: 'buffer' });
        const [sheetName] = workbook.SheetNames;
        const sheetInfo = workbook.Sheets[sheetName];
        if (!sheetInfo.A1 || sheetInfo.A1.v !== '蜂窝编号' || !sheetInfo.B1 || sheetInfo.B1.v !== '竞对名称') {
          Notification({
            title: '错误',
            message: '模板格式错误',
            type: 'error',
          });
          return;
        }
        const parsedSheetInfo = XLSX.utils.sheet_to_json(sheetInfo);
        const result = parsedSheetInfo.map((item, index) => ({
          rowNo: index + 1,
          topChannelCode: String(item['渠道编码'] || ''),
          cellularCode: String(item['蜂窝编号'] || ''),
          competeStoreName: String(item['竞对名称'] || ''),
        }));
        this.formValue.competeStores = result;
        this.$refs.formRef.validateField('competes');
        Notification({
          title: '提示',
          message: '文件上传成功',
          type: 'success',
        });
      };
      reader.readAsArrayBuffer(file.raw);
    },
    onError(err) {
      console.log('err:', err);
      Notification({
        title: '错误',
        message: '文件上传失败',
        type: 'error',
      });
    },
    //模板下载
    downImportTemplate() {
      window.location.href = './docs/批量导入蜂窝竞对信息模板.xlsx';
    },
    onCloseResultModal() {
      this.resultVisible = false;
    },
  },
  mounted() {},
};
